package com.example.ice.fittime.util;


import android.content.Context;

import com.example.ice.fittime.dao.DaoMaster;
import com.example.ice.fittime.dao.DaoSession;

import retrofit2.http.HEAD;

import static okhttp3.internal.Internal.instance;

/**
 * Created by Administrator on 2016/10/13.
 */

public class DaoManage {
    private static final String DB_NAME = "FitTime.db";
    private volatile static DaoManage daoManage;
    public static DaoMaster.DevOpenHelper helper;
    public static DaoMaster daoMaster;
    public static DaoSession daoSession;
    private Context context;

    public static DaoManage getInstance() {
        if (daoManage == null) {
            synchronized (DaoManage.class) {
                if (instance == null) {
                    daoManage = new DaoManage();
                }
            }
        }
        return daoManage;
    }

    public void init(Context context) {
        this.context = context;
    }

    public DaoMaster getDaoMaster() {
        if (daoMaster == null) {
            DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, DB_NAME, null);
            daoMaster = new DaoMaster(helper.getWritableDatabase());
        }
        return daoMaster;
    }


    public DaoSession getDaoSession() {
        if (daoSession == null) {
            if (daoMaster == null) {
                daoMaster = getDaoMaster();
            }
            daoSession = daoMaster.newSession();
        }
        return daoSession;
    }

    public void closeConnection() {
        closeHelper();
        closeDaoSession();
    }

    public void closeHelper() {
        if (helper != null) {
            helper.close();
            helper = null;
        }
    }

    public void closeDaoSession() {
        if (daoSession != null) {
            daoSession.clear();
            daoSession = null;
            if (daoSession != null) {
                daoSession.clear();
            }
        }
    }
}
